package org.hepeng.workx.spring.cloud.config;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.BooleanUtils;
import org.joor.Reflect;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.cloud.config.server.environment.JGitEnvironmentRepository;

import java.util.Map;

/**
 * @author he peng
 */
public class SimpleAlterConfigRepositoryParamHandler extends AbstractAlterConfigRepositoryParamHandler {

    @Override
    protected EnvironmentRepository handleGitRepository(JGitEnvironmentRepository repository, Map<String, Object> requestParam) {
        if (MapUtils.isEmpty(requestParam)) {
            return repository;
        }
        repository.setBasedir(Reflect.on(repository).call("createBaseDir").get());
        repository.setUri((String) requestParam.getOrDefault("uri" , ""));
        repository.setDefaultLabel((String) requestParam.getOrDefault("defaultLabel" , ""));
        repository.setUsername((String) requestParam.getOrDefault("username" , ""));
        repository.setPassword((String) requestParam.getOrDefault("password" , ""));
        if (requestParam.containsKey("searchPaths")) {
            repository.setSearchPaths((String) requestParam.get("searchPaths"));
        }

        if (requestParam.containsKey("deleteUntrackedBranches")) {
            repository.setDeleteUntrackedBranches(BooleanUtils.toBoolean((String) requestParam.get("deleteUntrackedBranches")));
        }

        if (requestParam.containsKey("forcePull")) {
            repository.setForcePull((Boolean) requestParam.get("forcePull"));
        }

        if (requestParam.containsKey("lastRefresh")) {
            repository.setLastRefresh((Long) requestParam.get("lastRefresh"));
        }

        if (requestParam.containsKey("refreshRate")) {
            repository.setRefreshRate((Integer) requestParam.get("refreshRate"));
        }

        if (requestParam.containsKey("skipSslValidation")) {
            repository.setSkipSslValidation((Boolean) requestParam.get("skipSslValidation"));
        }

        if (requestParam.containsKey("timeout")) {
            repository.setTimeout((Integer) requestParam.get("timeout"));
        }

        if (requestParam.containsKey("strictHostKeyChecking")) {
            repository.setStrictHostKeyChecking((Boolean) requestParam.get("strictHostKeyChecking"));
        }
        return repository;
    }
}
